package com.guiji.quartz.task;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Copyright (C), 2018-2021
 * @FileName: MonitorSeleniumGifTask
 * @Author: scl
 * @Date: 2021/9/24 11:03
 * @Description: 监控服务，生成gif推送到钉钉群里
 */
@Component("monitorSeleniumGifTask")
public class MonitorSeleniumGifTask {

	private static final Logger log = LoggerFactory.getLogger(MonitorSeleniumGifTask.class);

	public List<File> monitorSeleniumGifTask() throws IOException, InterruptedException {
		WebDriver chromeDriver = null;
		try {
			chromeDriver = getFirefoxDriver();
		} catch (Exception e) {
			log.info("已经登录");
		}
		String[] urls = new String[3];
		urls[0] = "http://172.16.6.71:5601/app/dashboards#/view/AV4REOpp5NkDleZmzKkE-ecs?_g=(filters:!(),refreshInterval:(pause:!f,value:10000),time:(from:now-1h,to:now))&_a=(description:'Overview%20of%20docker%20containers',filters:!(),fullScreenMode:!f,options:(darkTheme:!f),query:(language:kuery,query:''),tags:!(),timeRestore:!f,title:'%5BMetricbeat%20Docker%5D%20Overview%20ECS',viewMode:view)";
		urls[1] = "http://172.16.6.71:5601/app/dashboards#/view/57b3fb50-6309-11ea-a83e-25b8612d00cc?_g=(filters:!(),refreshInterval:(pause:!f,value:10000),time:(from:now-1h,to:now))&_a=(description:'Overview%20of%20MySQL%20server',filters:!(),fullScreenMode:!f,options:(darkTheme:!f,useMargins:!t),query:(language:kuery,query:''),tags:!(),timeRestore:!f,title:'%5BMetricbeat%20MySQL%5D%20Database%20Overview',viewMode:view)";
		urls[2] = "http://172.16.6.71:5601/app/dashboards#/view/Metricbeat-system-overview-ecs?_g=(filters:!(),refreshInterval:(pause:!f,value:10000),time:(from:now-1h,to:now))&_a=(description:'Overview%20of%20system%20metrics',filters:!(),fullScreenMode:!f,options:(darkTheme:!f),query:(language:kuery,query:''),tags:!(),timeRestore:!f,title:'%5BMetricbeat%20System%5D%20Overview%20ECS',viewMode:view)";
		List<File> list = new ArrayList<>();
		Thread.sleep(30000);
		list.add(((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE));
		for (int i = 0; i < 3; i++) {
			File file = mainMethod(urls[i], i, chromeDriver);
			list.add(file);
		}
		chromeDriver.quit();
		chromeDriver.close();
		return list;
	}

	public File mainMethod(String url, Integer i,WebDriver chromeDriver) throws IOException, InterruptedException {
		// 获取到截图的文件
		log.info("main================main"+chromeDriver.getCurrentUrl());
		chromeDriver.get(url);
		Thread.sleep(40000L);
		File screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
		return screenshotFile;
	}

	/**
	 * 单例获取一个，已经登录WebDriver
	 */
	public static WebDriver getFirefoxDriver() {


		ChromeDriver chromeDriver = null;
		try {
			String osys = System.getProperty("os.name").substring(0, 1);
			String chromedriver = "/usr/bin/chromedriver";
			String chrome = "/opt/google/chrome/chrome";
			if ("w".equalsIgnoreCase(osys)) {
				chromedriver = "C:\\Users\\Administrator\\AppData\\Local\\google\\Chrome\\Application\\chromedriver.exe";
				chrome = "C:\\Users\\Administrator\\AppData\\Local\\google\\Chrome\\Application\\chrome.exe";
			} else {

			}
			System.setProperty("webdriver.chrome.driver", chromedriver);
			System.setProperty("webdriver.chrome.bin", chrome);
			System.setProperty("webdriver.chrome.marionette", chrome);

			ChromeOptions chromeOptions = new ChromeOptions();
			//无页面使用
			chromeOptions.addArguments("--headless");
			//解决DevToolsActivePort文件不存在的报错
			chromeOptions.addArguments("--no-sandbox");
			//指定浏览器分辨率
			chromeOptions.addArguments("window-size=1920x1080");
			//谷歌文档提到需要加上这个属性来规避bug
			chromeOptions.addArguments("--disable-gpu");
			//不加载图片, 提升速度
			//chromeOptions.addArguments("blink-settings=imagesEnabled=false");
			//手动指定使用的浏览器位置
			//chromeOptions.setBinary("/usr/bin/google-chrome");
			chromeDriver = new ChromeDriver(chromeOptions);
			//通过driver控制浏览器打开链接（url）
			chromeDriver.get("http://172.16.6.71:5601/login?msg=LOGGED_OUT");
			// 休眠1s,为了让js执行完
			Thread.sleep(1000L);
			//最大化浏览器窗口
			chromeDriver.manage().window().maximize();
			// 页面等待渲染时长，如果你的页面需要动态渲染数据的话一定要留出页面渲染的时间，单位默认是秒
			Wait<WebDriver> wait = new WebDriverWait(chromeDriver, 3);
			//wait.until(ExpectedConditions.presenceOfElementLocated(By.className("chrome-headless")));
			Thread.sleep(3000L);
			chromeDriver.findElement(By.xpath("//input[@name='username']")).sendKeys(new String[]{"elastic"});
			chromeDriver.findElement(By.xpath("//input[@name='password']")).sendKeys(new String[]{"guiji2021"});
			chromeDriver.findElement(By.xpath("//button[@type='submit']")).click();
			log.info("mail1111111111111111111111111");
			return chromeDriver;
		} catch (Exception e) {
			log.info("oh, no Exception");
			e.printStackTrace();
		}
		log.info("mail22222222222222222222222");
		return null;
	}
}
